package com.example.administrator.yanfoxconn.activity;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.ClipData;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.TextView;

import com.example.administrator.yanfoxconn.R;
import com.example.administrator.yanfoxconn.constant.FoxContext;
import com.example.administrator.yanfoxconn.utils.BaseActivity;
import com.itheima.view.BridgeWebView;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 跳轉網頁 碼頭 或 協管開單 或巡檢報表
 * Created by song on 2017/10/27.
 */

public class WebViewTestActivity extends BaseActivity implements View.OnClickListener{
    @BindView(R.id.tv_title)
    TextView tvTitle;//標題
    @BindView(R.id.btn_title_left)
    Button btnBack;//返回
    private BridgeWebView webView;
    WebSettings mWebSettings;
    private ValueCallback<Uri> mUploadMessage;
    private ValueCallback<Uri[]> mUploadCallbackAboveL;
    private int FILECHOOSER_RESULTCODE = 200;
    private String role,jmUrl;//權限
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test_webview);
        ButterKnife.bind(this);

        btnBack.setOnClickListener(this);

        Bundle bundle = this.getIntent().getExtras();
        role = bundle.getString("role");


        if (role.equals("JK")) {
            tvTitle.setText("簽到記錄");
        }else if (role.equals("JL")) {//安保
            tvTitle.setText("E化放行");
        }else if (role.equals("LL")) {//碼頭-夏小龍
            tvTitle.setText("E化放行");
        }else if (role.equals("JM")) {//協管
            tvTitle.setText("E化放行");
            jmUrl=bundle.getString("url");
        }else if (role.equals("LO")) {//安保部-集中區放行
            tvTitle.setText("集中區放行");
        }else{
            tvTitle.setText("工作互聯");
        }

//        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
//                WindowManager.LayoutParams.FLAG_FULLSCREEN);//隐藏状态栏

        webView = (BridgeWebView)findViewById(R.id.activity_test_webView);
        //String url = "https://hhs.sdzjdxu.com/healthview/WorkPlatform/login.html";//带Echarts图表的网址
        mWebSettings = webView.getSettings();
        //localStorage  允许存储
        mWebSettings.setDomStorageEnabled(true);
        mWebSettings.setJavaScriptEnabled(true);
        mWebSettings.setAllowContentAccess(true);
        mWebSettings.setUseWideViewPort(true);//设定支持viewport
        mWebSettings.setLoadWithOverviewMode(true);
        mWebSettings.setBuiltInZoomControls(true);
        //mWebSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        mWebSettings.setSupportZoom(true);//设定支持缩放
        //mWebview.setDefaultHandler(new DefaultHandler());
        mWebSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        //localStorage  允许存储
        mWebSettings.setDomStorageEnabled(true);
        mWebSettings.setAllowFileAccess(true);
        mWebSettings.setAppCacheEnabled(true);
        mWebSettings.setLoadsImagesAutomatically(true) ;//支持自动加载图片
        //关键setGeolocationEnabled
        mWebSettings.setGeolocationEnabled(true);//开启定位

        if (role.equals("JK")){
            webView.loadUrl("https://ytsafeserver.foxconn.com:8080/driverCheckIn/#/List?id="+getIntent().getStringExtra("num"));
            //Log.e("-----","https://ytsafeserver.foxconn.com:8080/driverCheckIn/#/List?id="+getIntent().getStringExtra("num"));
        }else if (role.equals("JL")){
            //TODO 安保部
            webView.loadUrl("https://ytsafeserver.foxconn.com:8080/Car_record/goods_e/jump.jsp?no="+getIntent().getStringExtra("id")+"/"+FoxContext.getInstance().getLoginId()+"/JL");
            Log.e("-----",   "https://ytsafeserver.foxconn.com:8080/Car_record/goods_e/jump.jsp?no=" + getIntent().getStringExtra("id") + "/" + FoxContext.getInstance().getLoginId() + "/JL");
        }else if (role.equals("LL")){
            //TODO 碼頭-夏小龍
            webView.loadUrl("https://ytsafeserver.foxconn.com:8080/Car_record/goods_e/jump.jsp?no="+getIntent().getStringExtra("id")+"/"+FoxContext.getInstance().getLoginId()+"/LL");
            Log.e("-----",   "https://ytsafeserver.foxconn.com:8080/Car_record/goods_e/jump.jsp?no=" + getIntent().getStringExtra("id") + "/" + FoxContext.getInstance().getLoginId() + "/LL");
        }else if (role.equals("JM")) {
            //TODO 協管
            webView.loadUrl(jmUrl);
            Log.e("-----",jmUrl);

//            webView.loadUrl("https://ytsafeserver.foxconn.com:8080/Car_record/goods_e/jump.jsp?no=" + getIntent().getStringExtra("id") + "/" + FoxContext.getInstance().getLoginId() + "/JM");
//            Log.e("-----",   "http://192.168.1.128:8080/Car_record/goods_e/jump.jsp?no=" + getIntent().getStringExtra("id") + "/" + FoxContext.getInstance().getLoginId() + "/JM");
        }else if (role.equals("LO")) {
            //TODO 安保部-集中區放行http://192.168.43.203:8088/Server/
            webView.loadUrl("https://ytsafeserver.foxconn.com:8080/Car_record/goods_e/jump_hm.jsp?no="+getIntent().getStringExtra("id")+"/"+FoxContext.getInstance().getLoginId()+"/JL");
//            webView.loadUrl("https://192.168.43.203:8088/Car_record/goods_e/jump_hm.jsp?no="+getIntent().getStringExtra("id")+"/"+FoxContext.getInstance().getLoginId()+"/LO");
            Log.e("-----",   "https://ytsafeserver.foxconn.com:8080/Car_record/goods_e/jump_hm.jsp?no" + getIntent().getStringExtra("id") + "/" + FoxContext.getInstance().getLoginId() + "/LO");
       }else{
            webView.loadUrl("https://hhs.sdzjdxu.com/healthview/WorkPlatform/login.html");
        }


        //设置不用系统浏览器打开,直接显示在当前Webview
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }

        });

        //设置WebChromeClient类
        webView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onGeolocationPermissionsShowPrompt(String origin,android.webkit.GeolocationPermissions.Callback callback) {
                callback.invoke(origin, true, false);
                super.onGeolocationPermissionsShowPrompt(origin, callback);
            }
            public void openFileChooser(ValueCallback<Uri> uploadMsg) {
                //Log.d(TAG, "openFileChoose(ValueCallback<Uri> uploadMsg)");
                mUploadMessage = uploadMsg;
                Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                i.addCategory(Intent.CATEGORY_OPENABLE);
                i.setType("image/*");
                WebViewTestActivity.this.startActivityForResult(Intent.createChooser(i, "File Chooser"),
                        FILECHOOSER_RESULTCODE);
            }

            public void openFileChooser( ValueCallback uploadMsg, String acceptType ) {
                //Log.d(TAG, "openFileChoose( ValueCallback uploadMsg, String acceptType )");
                mUploadMessage = uploadMsg;
                Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                i.addCategory(Intent.CATEGORY_OPENABLE);
                i.setType("image/*");
                WebViewTestActivity.this.startActivityForResult(
                        Intent.createChooser(i, "File Browser"),FILECHOOSER_RESULTCODE);
            }

            public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture){
                //Log.d(TAG, "openFileChoose(ValueCallback<Uri> uploadMsg, String acceptType, String capture)");
                mUploadMessage = uploadMsg;
                Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                i.addCategory(Intent.CATEGORY_OPENABLE);
                i.setType("image/*");
                WebViewTestActivity.this.startActivityForResult( Intent.createChooser( i, "File Browser" ), FILECHOOSER_RESULTCODE );
            }

            public boolean onShowFileChooser (WebView webView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams) {
                mUploadCallbackAboveL = filePathCallback;
                Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                i.addCategory(Intent.CATEGORY_OPENABLE);
                i.setType("image/*");
                WebViewTestActivity.this.startActivityForResult(
                        Intent.createChooser(i, "File Browser"),
                        FILECHOOSER_RESULTCODE);
                return true;
            }

        });
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode==FILECHOOSER_RESULTCODE){
            if (null == mUploadMessage && null == mUploadCallbackAboveL) return;
            Uri result = data == null || resultCode != RESULT_OK ? null : data.getData();
            if (mUploadCallbackAboveL != null) {
                onActivityResultAboveL(requestCode, resultCode, data);
            }
            else  if (mUploadMessage != null) {
                mUploadMessage.onReceiveValue(result);
                mUploadMessage = null;
            }
        }
    }


    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    private void onActivityResultAboveL(int requestCode, int resultCode, Intent data) {
        if (requestCode != FILECHOOSER_RESULTCODE|| mUploadCallbackAboveL == null) {
            return;
        }
        Uri[] results = null;
        if (resultCode == Activity.RESULT_OK) {
            if (data == null) {

            } else {
                String dataString = data.getDataString();
                ClipData clipData = data.getClipData();
                if (clipData != null) {
                    results = new Uri[clipData.getItemCount()];
                    for (int i = 0; i < clipData.getItemCount(); i++) {
                        ClipData.Item item = clipData.getItemAt(i);
                        results[i] = item.getUri();
                    }
                }

                if (dataString != null)
                    results = new Uri[]{Uri.parse(dataString)};
            }
        }
        mUploadCallbackAboveL.onReceiveValue(results);
        mUploadCallbackAboveL = null;
        return;
    }

    //点击返回上一页面而不是退出浏览器
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && webView.canGoBack()) {
            webView.goBack();
            return true;
        }

        return super.onKeyDown(keyCode, event);
    }

    //销毁Webview
    @Override
    protected void onDestroy() {
        if (webView != null) {
            webView.loadDataWithBaseURL(null, "", "text/html", "utf-8", null);
            webView.clearHistory();

            ((ViewGroup) webView.getParent()).removeView(webView);
            webView.destroy();
            webView = null;
        }
        CookieSyncManager.createInstance(this);
        CookieManager.getInstance().removeAllCookie();
        super.onDestroy();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.btn_title_left:
                finish();
                break;
        }
    }
}
